package com.sgcc.fj.pmos.mobileapp.fragment;

import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.utils.TextUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.sgcc.fj.pmos.common.base.MvpBaseFragment;
import com.sgcc.fj.pmos.common.http.HttpInterConst;
import com.sgcc.fj.pmos.common.http.HttpRequestUtils;
import com.sgcc.fj.pmos.common.http.MvcNetCallback;
import com.sgcc.fj.pmos.common.utils.SysUtil;
import com.sgcc.fj.pmos.common.widget.MyEditText;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.fj.pmos.mobileapp.activity.AssociatedEnterpriseInfoActivity;
import com.sgcc.fj.pmos.mobileapp.bean.DefaultContactInfoBean;
import com.sgcc.fj.pmos.mobileapp.bean.GeographicregionBean;
import com.sgcc.fj.pmos.mobileapp.bean.QueryContactInfoBean;
import com.sgcc.fj.pmos.mobileapp.bean.StatusBean;
import com.sgcc.fj.pmos.mobileapp.bean.StringDataBean;
import com.sgcc.fj.pmos.mobileapp.contract.ContactInfoContract;
import com.sgcc.fj.pmos.mobileapp.dialog.CommunicationAreaPopup;
import com.sgcc.fj.pmos.mobileapp.dialog.GeographicalAreaPopup;
import com.sgcc.fj.pmos.mobileapp.presenter.ContactInfoPresenter;
import com.sgcc.fj.pmos.mobileapp.utils.OnNextListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


/**
 * @author ChaoAJ
 * @describe 关联企业信息--联系信息
 * @time 2022/10/18 11:56
 */
public class ContactInfoFragment extends MvpBaseFragment<ContactInfoPresenter> implements
        ContactInfoContract.View {


    private RelativeLayout mRlGeographicalArea;
    private TextView mTvGeographicalArea;
    private MyEditText mEtPostalcode;
    private MyEditText mEtLandlineNumber;
    private RelativeLayout mRlCommunicationArea;
    private TextView mTvCommunicationArea;
    private MyEditText mEtAddress;
    private OnNextListener mOnNextListener;
    private String mGeogrRegionId = null;
    private boolean isLeaf = false;//是否最后一级
    private String mValues = null;

    private boolean isQueryContactInfoNull = false;


    public static ContactInfoFragment newInstance() {
        ContactInfoFragment fragment = new ContactInfoFragment();
        return fragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_contact_info;
    }

    @Override
    protected ContactInfoPresenter createPresenter() {
        return new ContactInfoPresenter();
    }

    @Override
    protected void initViews() {
        super.initViews();
        findViewByIds();
        setViewAction();
        mPresenter.queryContactInfo();
        mPresenter.queryDefaultContactInfo();
    }

    private void setViewAction() {
        mRlGeographicalArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new XPopup.Builder(getContext())
                        .moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .asCustom(new GeographicalAreaPopup(mContext, new GeographicalAreaPopup.OnCallBackListener() {
                            @Override
                            public void save(String address, String geogrRegionId, GeographicregionBean.DataBean dataBean) {
                                mGeogrRegionId = geogrRegionId;
                                ContactInfoFragment.this.isLeaf = dataBean.isLeaf();
                                mEtPostalcode.setText(dataBean.getPostcode());
                                mEtLandlineNumber.setText(dataBean.getAreaCode() + "-");
                                mTvGeographicalArea.setText(address);
                            }
                        }))
                        .show();
            }
        });
        mRlCommunicationArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new XPopup.Builder(getContext())
                        .moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .asCustom(new CommunicationAreaPopup(mContext, new CommunicationAreaPopup.OnCallBackListener() {
                            @Override
                            public void save(String values, String lables) {
                                mValues = values;
                                String lable = lables.replace(",", "");
                                mTvCommunicationArea.setText(lable);
                            }
                        }))
                        .show();
            }
        });
    }

    private void findViewByIds() {
        mRlGeographicalArea = (RelativeLayout) mRootView.findViewById(R.id.rl_GeographicalArea);
        mTvGeographicalArea = (TextView) mRootView.findViewById(R.id.tv_GeographicalArea);
        mEtPostalcode = (MyEditText) mRootView.findViewById(R.id.et_postalcode);
        mEtLandlineNumber = (MyEditText) mRootView.findViewById(R.id.et_LandlineNumber);
        mRlCommunicationArea = (RelativeLayout) mRootView.findViewById(R.id.rl_CommunicationArea);
        mTvCommunicationArea = (TextView) mRootView.findViewById(R.id.tv_CommunicationArea);
        mEtAddress = (MyEditText) mRootView.findViewById(R.id.et_address);
    }

    public void next(OnNextListener onNextListener) {
        mOnNextListener = onNextListener;
        if (TextUtils.isEmpty(mGeogrRegionId)) {
            ToastUtils.showShort("请选择地理区域");
            mOnNextListener.onNext(false);
            return;
        }
        if (!isLeaf) {
            ToastUtils.showShort("请选择最后一级地理区域");
            mOnNextListener.onNext(false);
            return;
        }

        String postalcode = mEtPostalcode.getText().toString().trim();
        if (TextUtils.isEmpty(postalcode)) {
            ToastUtils.showShort("请输入邮政编码");
            mOnNextListener.onNext(false);
            return;
        }

        String landlineNumber = mEtLandlineNumber.getText().toString().trim();
        if (TextUtils.isEmpty(landlineNumber)) {
            ToastUtils.showShort("请输入固话号码");
            mOnNextListener.onNext(false);
            return;
        }
        if (!SysUtil.isTelCard(landlineNumber)) {
            ToastUtils.showShort("固话号码格式错误");
            mOnNextListener.onNext(false);
            return;
        }

        if (TextUtils.isEmpty(mValues)) {
            ToastUtils.showShort("请选择通信所在地区");
            mOnNextListener.onNext(false);
            return;
        }

        String address = mEtAddress.getText().toString().trim();
        if (TextUtils.isEmpty(address)) {
            ToastUtils.showShort("请输入通信详细地址");
            mOnNextListener.onNext(false);
            return;
        }

        Map<String, Object> params = new HashMap<>();
        params.put("geogrregionId", mGeogrRegionId);
        params.put("postalcode", postalcode);
        params.put("telPre", "");
        params.put("tel", landlineNumber);
        params.put("districtsId", mValues.split(","));
        params.put("address", address);
        params.put("companyId", "123456");
        params.put("membersId", "123456");
        mPresenter.saveContactInfo(params);

    }

    @Override
    public void saveContactInfoSuccess(StatusBean response) {
        if (mOnNextListener != null) {
            mOnNextListener.onNext(true);
        }
    }

    @Override
    public void queryContactInfoSuccess(QueryContactInfoBean response) {
        if (response.getData() != null) {
            if (!response.getData().isEmpty()) {
                QueryContactInfoBean.DataBean dataBean = response.getData().get(0);
                if (dataBean != null) {
                    queryName(dataBean.getGeogrregionId());
                    mGeogrRegionId = dataBean.getGeogrregionId();
                    isLeaf = true;
                    mEtPostalcode.setText(dataBean.getPostalcode());
                    mEtLandlineNumber.setText(dataBean.getTel());
                    mEtAddress.setText(TextUtils.isEmpty(dataBean.getAddress()) ?
                            ((AssociatedEnterpriseInfoActivity) getActivity()).getRegAddress().trim() : dataBean.getAddress());
                } else {
                    isQueryContactInfoNull = true;
                }

            }
        }

        mPresenter.queryDefaultContactInfo();
    }

    @Override
    public void defaultContactInfoSuccess(DefaultContactInfoBean.DataBean response) {
        List<DefaultContactInfoBean.DataBean.DistricsParamsBoDTO> districsParamsBo =
                response.getDistricsParamsBo();
        if (null != districsParamsBo && districsParamsBo.size() > 0) {
            DefaultContactInfoBean.DataBean.DistricsParamsBoDTO districsParamsBoDTO = districsParamsBo.get(0);
            if (null != districsParamsBoDTO) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(districsParamsBoDTO.getLabel());
                mValues = districsParamsBoDTO.getValue();
                String data = getData(stringBuilder, districsParamsBoDTO.getChildren());
                mTvCommunicationArea.setText(data);
            }
        }

        if (isQueryContactInfoNull) {
            mGeogrRegionId = response.getGeoId();
            isLeaf = true;
            queryName(response.getGeoId());
            mEtPostalcode.setText(response.getPostcode());
            mEtLandlineNumber.setText(response.getAreaCode() + "-");
            mEtAddress.setText(
                    ((AssociatedEnterpriseInfoActivity) getActivity()).getRegAddress().trim());

        }
    }

    private String getData(StringBuilder stringBuilder, List<DefaultContactInfoBean.DataBean.DistricsParamsBoDTO.ChildrenDTO> list) {

        for (DefaultContactInfoBean.DataBean.DistricsParamsBoDTO.ChildrenDTO child : list) {
            stringBuilder.append(child.getLabel());
            if (null != child.getChildren()) {
                mValues += child.getValue() + ",";
                getData(stringBuilder, child.getChildren());
            } else {
                mValues += child.getValue();
            }
        }
        return stringBuilder.toString();
    }


    private void queryName(String geogrRegionId) {
        Map<String, Object> params = new HashMap<>();
        params.put("geogrRegionId", geogrRegionId);
        HttpRequestUtils.getInstance().request(params, HttpInterConst.QUERYNAME, new MvcNetCallback<StringDataBean>(true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);

            }

            @Override
            public void onResponse(StringDataBean response, int id) {
                super.onResponse(response, id);

                if (response != null) {
                    if (response.getStatus() == 0 && "Success".equals(response.getMessage())) {
                        mTvGeographicalArea.setText(response.getData());
                    }
                }
            }
        });
    }

    public void getData() {
        mPresenter.queryContactInfo();
    }
}